package net.opslog.web.client.service;

import java.util.ArrayList;
import java.util.List;

import net.opslog.web.client.models.JSOModel;
import net.opslog.web.client.models.LogEntry;

import com.google.gwt.view.client.Range;

import com.google.gwt.core.client.JsArray;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.Response;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONValue;
import com.google.gwt.user.client.Window;
import com.google.gwt.view.client.AsyncDataProvider;
import com.google.gwt.view.client.HasData;

public class LogDataProvider extends AsyncDataProvider<LogEntry> {
	LogEntriesRequest request = new LogEntriesRequest();
	@Override
	protected void onRangeChanged(HasData<LogEntry> display) {
		

		final Range range = display.getVisibleRange();

		request.getLogEntries(new RequestCallback() {

			@Override
			public void onResponseReceived(Request request, Response response) {
				JSONValue jsonResponse = JSONParser.parseStrict(response.getText());
				JsArray<JSOModel> data = JSOModel.arrayFromJson(jsonResponse.isObject().get("content").isArray().toString());
				List<LogEntry> logEntries = new ArrayList<LogEntry>();
				for (int i = 0; i < data.length(); i++) {
					LogEntry logEntry = new LogEntry(data.get(i));
					logEntries.add(logEntry);
				}
				int start = range.getStart();
				int end = start + range.getLength();

				updateRowData(start, logEntries);

			}

			@Override
			public void onError(Request request, Throwable exception) {
				Window.alert(exception.getMessage());

			}

		});
	}

	public void setLogOrder(String order) {
		request.setParameter("sort", order);		
	}

}
